package com.deuwise.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.deuwise.common.validator.ValidatorUtils;
import com.deuwise.common.validator.group.AddGroup;
import com.deuwise.common.validator.group.UpdateGroup;
import com.deuwise.system.entity.SiteLayerModel;
import com.deuwise.system.entity.SysMenu;
import com.deuwise.system.entity.SysSiteLayer;
import com.deuwise.system.service.SysMenuService;
import com.deuwise.system.service.SysSiteLayerService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.system.entity.AppDo;
import com.deuwise.system.service.AppDoService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *@author deuwise
 *@date 2018-11-20 10:36:29
 */
@Api(tags = "注册系统模块", description = "注册系统模块")
@RequestMapping("api/appDO")
@RestController()
public class AppDoController extends AbstractController {
    @Autowired
    private AppDoService appDoService;

    /**
     * 应用信息
     */
    @GetMapping("/{Id}")
    @RequiresPermissions("sys:app:info")
    public Result<AppDo> info(@PathVariable("Id") String id){
        AppDo appDo = appDoService.selectById(id);
        return  Result.ok(appDo);
    }

    @ApiOperation(value = "根据code获取详情")
    @GetMapping("/getInfoByCode/{code}")
    public Result<AppDo> getInfoByCode(@PathVariable("code") String code){
        Wrapper<AppDo> wrapper=new EntityWrapper<>();
        wrapper.like("code", code);
        AppDo appDo = appDoService.selectOne(wrapper);
        return  Result.ok(appDo);
    }

    @ApiOperation(value = "应用list", notes = "应用list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("sys:app:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "应用名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<AppDo>> list(String name,String code){
        Wrapper<AppDo> wrapper=new EntityWrapper<>();
        wrapper.orderBy("create_time", false).orderBy("update_time", false);
        if(StringUtils.isNotBlank(name)) {
            wrapper.like("name", name);
        }
        if(StringUtils.isNotBlank(code)) {
            wrapper.like("code", code);
        }
        wrapper.orderBy("id",false);
        Page<AppDo> appDoPage=appDoService.selectPage(getPage(AppDo.class),wrapper);
        return Result.ok(appDoPage);
    }

    @ApiOperation(value = "新增数据")
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @RequiresPermissions("sys:app:save")
    public R insertApp(@RequestBody AppDo appDo){
        ValidatorUtils.validateEntity(appDo, AddGroup.class);
        boolean isSuccess = false;
        if(null == appDo){
            return R.error(200,"新增数据失败，请稍后再试!");
        }
        int count=appDoService.queryByName(appDo.getName(),null);
        if(count>0){
            return R.error(200,"应用名称不能重复");
        }
        int countCode=appDoService.queryByName(appDo.getCode(),null);
        if(countCode>0){
            return R.error(200,"编码不能重复");
        }
        appDo.setCreateTime(new Date());
        appDo.setUpdateTime(new Date());
        isSuccess = appDoService.insert(appDo);
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(200,"新增数据失败，请稍后再试!");
        }
    }
    @ApiOperation("删除应用")
    @DeleteMapping("/{id}")
    @RequiresPermissions("sys:app:delete")
    public R delete(@PathVariable("id") String id){
        boolean result=appDoService.deleteById(id);
        return R.ok(result);
    }
    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation(value = "编辑数据")
    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @RequiresPermissions("sys:app:update")
    public R updateApp(@RequestBody AppDo appDo){
        try {
            boolean isSuccess = false;
            if (null == appDo) {
                return R.error(200, "数据编辑失败，请稍后再试!");
            }
            int count = appDoService.queryByName(appDo.getName(), appDo);
            if (count > 0) {
                return R.error(200, "应用名称不能重复");
            }
            int countCode = appDoService.queryByName(appDo.getCode(), appDo);
            if (countCode > 0) {
                return R.error(200, "编码不能重复");
            }
            if (appDo.getCode().equals("dwAdmin") && appDo.getStatus() == 0) {
                return R.error(200, "默认应用不能被禁用");
            }
            ValidatorUtils.validateEntity(appDo, UpdateGroup.class);
            appDo.setUpdateTime(new Date());
            AppDo oldAppDo = appDoService.selectById(appDo.getId());
            isSuccess = appDoService.updateById(appDo);
            if (isSuccess) {
                if (!oldAppDo.getCode().equals(appDo.getCode())) {
                    Wrapper<SysMenu> wrapper = new EntityWrapper<>();
                    wrapper.eq("app_id", oldAppDo.getCode());
                    List<SysMenu> sysMenuList = sysMenuService.selectList(wrapper);
                    for (SysMenu menu : sysMenuList) {
                        menu.setAppId(appDo.getCode());
                    }
                    if(sysMenuList!=null&&sysMenuList.size()>0) {
                        sysMenuService.updateBatchById(sysMenuList);
                    }
                }
                return R.ok();
            } else {
                return R.error(200, "数据编辑失败，请稍后再试!");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error(200, "数据编辑失败，请稍后再试!");
        }
    }

    @ApiOperation(value = "批量删除记录")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.GET)
    @RequiresPermissions("sys:app:delete")
    public  R deleteSelect(@ApiParam(value = "ids集合",name = "ids",required = true) @RequestParam String[] ids){
        try {
            if (ids != null && ids.length > 0) {
                    appDoService.deleteBatchIds(Arrays.asList(ids));
            }
        }catch (Exception ex){
            return  R.error("删除失败");
        }
        return  R.ok();
    }
    @Autowired
    private SysSiteLayerService layerService;

    @ApiOperation("获取图层list根据系统Id")
    @GetMapping("getLayerId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应用名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "category", value = "图层类别2d/3d", dataType = "String", paramType = "query")})
    public R getLayerId(String id, String category) {
        List<String> list = layerService.queryLayerList(id, category);
        return R.ok(list);
    }

    @ApiOperation("获取视图list根据系统Id")
    @GetMapping("getMapViewId")
    @RequiresPermissions("sys:app:map")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "应用名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "category", value = "图层类别2d/3d", dataType = "String", paramType = "query")})
    public R getMapViewId(String id, String category) {
        String mapViewId = layerService.queryMapViewBySiteId(id, category);
        return R.ok(mapViewId);
    }

    @ApiOperation("修改站点图层对象")
    @PutMapping("/updateSiteLayer")
    @ApiImplicitParam(name = "siteLayerModel", value = "站点图层对象", required = true, dataType = "SiteLayerModel", paramType = "body")
    public R update(@RequestBody SiteLayerModel siteLayerModel) {
        if(siteLayerModel!=null&&StringUtils.isNotBlank(siteLayerModel.getSiteId())) {
            layerService.saveOrUpdate(siteLayerModel.getCategory(),siteLayerModel.getSiteId(),
                    siteLayerModel.getLayerId(), siteLayerModel.getMapViewId());
        }else{
            return  R.error("站点id不能为空");
        }
        return  R.ok();
    }


}